<template>
  <div>
    <el-card class="login-form-layout">
      <el-form autoComplete="on" :model="loginForm" :rules="loginRules" ref="loginForm" label-position="left">
        <div style="text-align: center">
          <svg-icon icon-class="login-mall" style="width: 56px; height: 56px; color: #409eff"></svg-icon>
        </div>
        <h2 class="login-title color-main">管理平台</h2>
        <el-form-item prop="username">
          <el-input name="username" type="text" v-model="loginForm.username" autoComplete="on" placeholder="请输入用户名">
            <span slot="prefix">
              <svg-icon icon-class="user" class="color-main"></svg-icon>
            </span>
          </el-input>
        </el-form-item>

        <el-form-item prop="password">
          <el-input name="password" :type="pwdType" @keyup.enter.native="handleLogin" v-model="loginForm.password"
            autoComplete="on" placeholder="请输入密码">
            <span slot="prefix">
              <svg-icon icon-class="password" class="color-main"></svg-icon>
            </span>
            <span slot="suffix" @click="showPwd">
              <svg-icon icon-class="eye" class="color-main"></svg-icon>
            </span>
          </el-input>
        </el-form-item>

        <el-form-item prop="code">
          <el-input name="code" class="code-input" type="text" v-model="loginForm.code" autoComplete="on"
            placeholder="请输入验证码">
          </el-input>
          <!-- 获取验证码展示 -->
          <img id="captchaImg" style="width: 100px;height: 38px;margin-left: 20px;cursor: pointer;"
            @click="refreshCaptcha" :src="captchaImg">
          <!-- <img id="captchaImg" style="width: 100px;height: 38px;margin-left: 20px;cursor: pointer;" @click="refreshCaptcha"
            src="http://192.168.10.122:8080/user/captcha"> -->
        </el-form-item>

        <el-form-item style="text-align: center">
          <el-button style="width: 100%" type="primary" :loading="loading" @click.native.prevent="handleLogin">
            登录
          </el-button>
        </el-form-item>
        <el-form-item style="margin-bottom: 10px; text-align: center;width: 100%;" class="el-form-item-span">
          <span style="text-align: center;" @click="registerData()">注册</span>
        </el-form-item>
      </el-form>
    </el-card>
    <img :src="login_center_bg" class="login-center-layout" />
    <el-dialog title="注册" :visible.sync="dialogVisible" width="400px" :before-close="closeData">
      <el-form :model="register" ref="roleForm" label-width="100px" size="small" :rules="registerRules">
        <el-form-item label="账号：" prop="username">
          <el-input v-model="register.username" style="width: 250px"></el-input>
        </el-form-item>
        <el-form-item label="密码：" prop="password">
          <el-input v-model="register.password" style="width: 250px"></el-input>
        </el-form-item>
        <el-form-item label="确认密码：" prop="isPassword">
          <el-input v-model="register.isPassword" style="width: 250px"></el-input>
        </el-form-item>
        <el-form-item label="手机号：">
          <el-input v-model="register.phone" style="width: 250px"></el-input>
        </el-form-item>
        <el-form-item label="邮箱：">
          <el-input v-model="register.email" style="width: 250px"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="closeData()" size="small">取 消</el-button>
        <el-button type="primary" @click="handleDialogConfirm()" size="small">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { isvalidUsername } from "@/utils/validate";
import { getCookie } from "@/utils/support";
import login_center_bg from "@/assets/images/login_center_bg.png";
import { getCode, register } from "@/api/login";


export default {
  name: "login",
  data() {
    const validateUsername = (rule, value, callback) => {
      if (!isvalidUsername(value)) {
        callback(new Error("请输入正确的用户名"));
      } else {
        callback();
      }
    };
    const validatePass = (rule, value, callback) => {
      if (value.length < 3) {
        callback(new Error("密码不能小于3位"));
      } else {
        callback();
      }
    };
    const validateCode = (rule, value, callback) => {
      if (value.length != 4) {
        callback(new Error("请输入4位数验证码"));
      } else {
        callback();
      }
    };
    return {
      loginForm: {
        username: "",
        password: "",
        code: "",
      },
      loginRules: {
        username: [
          { required: true, trigger: "blur", validator: validateUsername },
        ],
        password: [
          { required: true, trigger: "blur", validator: validatePass },
        ],
        code: [{ required: true, trigger: "blur", validator: validateCode }],
      },
      loading: false,
      pwdType: "password",
      // 背景图
      login_center_bg,
      captchaImg: '',
      captchaKey: '',
      dialogVisible: false,
      register: {
        username: '',
        password: '',
        isPassword: '',
        phone: '',
        email: ''
      },
      registerRules: {
        username: [{ required: true, trigger: "blur", validator: validateUsername }],
        password: [{ required: true, trigger: "blur", validator: validatePass }],
        isPassword: [{ required: true, message: "请输入", trigger: "blur" }],
      }
    };
  },
  created() {
    this.loginForm.username = getCookie("username");
    this.loginForm.password = getCookie("password");
    if (
      this.loginForm.username === undefined ||
      this.loginForm.username == null ||
      this.loginForm.username === ""
    ) {
      this.loginForm.username = "admin";
    }
    if (
      this.loginForm.password === undefined ||
      this.loginForm.password == null
    ) {
      this.loginForm.password = "123456";
    }
    this.refreshCaptcha()
  },
  methods: {
    // 获取验证码
    refreshCaptcha() {
      // const captchaImg = document.getElementById('captchaImg');
      // // 添加时间戳防止浏览器缓存旧验证码
      // captchaImg.src = "http://192.168.10.122:8080/user/captcha?t=" + new Date().getTime();
      getCode().then(res => {
        if (res.code == 200) {
          this.captchaImg = res.data.captchaImg
          this.captchaKey = res.data.captchaKey
        }
      })
    },
    // 密码显示隐藏切换
    showPwd() {
      if (this.pwdType === "password") {
        this.pwdType = "";
      } else {
        this.pwdType = "password";
      }
    },
    // 登录
    handleLogin() {
      this.$refs.loginForm.validate((valid) => {
        if (valid) {
          this.loading = true;
          this.$store
            .dispatch("Login", { ...this.loginForm, captchaKey: this.captchaKey })
            .then(() => {
              this.loading = false;
              this.$router.push({ path: "home" });
            })
            .catch(() => {
              this.loading = false;
            });
          // this.$router.push({path: '/'})
        } else {
          console.log("参数验证不合法！");
          return false;
        }
      });
    },
    // 注册
    registerData() {
      this.dialogVisible = true;
    },
    // 确认
    handleDialogConfirm() {
      this.$refs.roleForm.validate((valid) => {
        if (valid) {
          if (this.register.password == this.register.isPassword) {
            let par = {
              ...this.register
            }
            register(par).then(res => {
              if (res.code == 200) {
                this.$message({
                  type: 'success',
                  message: '注册成功!'
                });
                this.closeData()
              }
            })
          } else {
            this.$message({
              type: 'error',
              message: '两次密码不一致!'
            })
          }

        } else {
          return false;
        }
      });
    },
    // 关闭
    closeData() {
      this.register = {
        username: '',
        password: '',
        isPassword: '',
        phone: '',
        email: ''
      }
      this.dialogVisible = false;
    }
  },
};
</script>

<style lang="scss" scoped>
/deep/ .el-form-item__content {
  display: flex;
  align-items: center;

}

.el-form-item-span {
  display: flex;
  align-items: center;
  justify-content: center;

  span {
    cursor: pointer;
  }
}

.code-input {
  width: 150px;
}

.login-form-layout {
  position: absolute;
  left: 0;
  right: 0;
  width: 360px;
  margin: 140px auto;
  border-top: 10px solid #409eff;
}

.login-title {
  text-align: center;
}

.login-center-layout {
  background: #409eff;
  width: auto;
  height: auto;
  max-width: 100%;
  max-height: 100%;
  margin-top: 200px;
}
</style>
